<template>
  <div class="bot-container">
        <!-- 机器人图标 -->
      <div class="chatbot-icon" @click="toggleChatWindow">
        <img src="https://cdn-icons-png.flaticon.com/512/4712/4712035.png" alt="机器人">
      </div>
      
      <!-- 聊天窗口 -->
      <div class="chatbot-window" :class="{ active: isChatOpen }" v-if="isChatOpen">
        <div class="chatbot-header">
          <span>智能助手</span>
          <span class="chatbot-close" @click="toggleChatWindow">×</span>
        </div>
        <div class="chatbot-messages" ref="messages">
          <div v-for="(message, index) in messages" :key="index" class="message" :class="message.sender">
            {{ message.text }}
          </div>
        </div>
        <div class="chatbot-input">
         <div class="chatbot-input-actions">
          <button class="new-chat-btn" @click="startNewChat">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="12" y1="5" x2="12" y2="19"></line>
              <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
          </button>
        </div>
          <textarea rows="5" 
            v-model="userInput" 
            placeholder="请输入您的问题..." 
            @keyup.enter="sendMessage"
          />
          <button @click="sendMessage">发送</button>
        </div>
      </div>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js'
import {insertDaySale} from '@/js/db'
export default{
    name: 'chatBot',
    data () {
        return {
            url: 'wss://spark-api.xf-yun.com/v3.5/chat',
            appId: '94b07ed1',
            apiKey: '35974ce45434ceee1a1906ef63c3521d',
            apiSecret: 'NmE1ZjYzYmZjM2U5ZmI0M2JjYmE1ZTJk',
            reply: '',
            aiAnswer: '',
            isChatOpen: false,
            userInput: '',
            messages: [
                { text: '您好！我是小西AI助手，请问有什么可以帮您的吗？', sender: 'bot-message' }
            ],
            // 简单的问答知识库
            knowledgeBase: {
                '你好': '您好！很高兴为您服务。',
                '你好啊': '您好！有什么我可以帮助您的吗？',
                '你是谁': '我是您的小西AI助手，可以帮助解答问题。',
                '有什么功能': '我可以回答您的问题，提供帮助信息。',
                '谢谢': '不客气，很高兴能帮到您！',
                '再见': '再见！如果需要帮助随时可以找我。',
                '默认': '抱歉，我不太明白您的问题。您可以尝试换种方式提问。'
            }
        }
    },
    components:{

    },
    methods:{
        toggleChatWindow() {
            this.isChatOpen = !this.isChatOpen;
            if (this.isChatOpen) {
                this.$nextTick(() => {
                this.scrollToBottom();
                });
            }
        },
        sendMessage(event) {
            if (!this.userInput.trim()) return;
            if (event.key === 'Enter') {
               event.preventDefault();
               this.userInput += "\n"
            }
            
            // 添加用户消息
            this.messages.push({
                text: this.userInput,
                sender: 'user-message'
            });
            
            // 获取机器人回复
            this.getBotReply(this.userInput);
            this.userInput = '';
            this.scrollToBottom();
        },
        askKnownledge(input) {
            // 检查知识库中是否有匹配的回答
            for (const [question, answer] of Object.entries(this.knowledgeBase)) {
                if (input.includes(question.toLowerCase())) {
                  this.reply = answer
                   // 模拟机器人思考时间
                  setTimeout(() => {
                      this.messages.push({
                      text: this.reply,
                      sender: 'bot-message'
                      });
                      this.scrollToBottom();
                  }, 500);
                  break
                }
            }
        },
        parseSalesData(text) {
          const lines = text.trim().split('\n');
          let results = [];
          let currentDate = '';

          for (const line of lines) {
            const trimmedLine = line.trim();
            if(!trimmedLine){
              continue;
            }
            const currentYear = new Date().getFullYear();
            const dateMatch = trimmedLine.match(/(\d+)月(\d+)日/);
            if (dateMatch) {
              const month = dateMatch[1].padStart(2, '0');  // 补零
              const day = dateMatch[2].padStart(2, '0');    // 补零
              currentDate = `${currentYear}-${month}-${day}`; // 如 "2025-08-27"
              continue;
            }

            // 匹配销售记录：如 "安踏大店销售额12000元"
            const match = trimmedLine.match(/^(.+?)销售额(\d+)元$/);
            if (match) {
              const shopName = match[1];        // 完整店铺名，如 "安踏大店"
              const saleAmount = parseInt(match[2], 10); // 销售额数字

              results.push({
              day: currentDate,
              name: shopName,
              amount: saleAmount
              });
            }
          // 如果行不匹配，可选择忽略或报错
          }
          return results;
        },
        async askRule2(input) {
          //蜘蛛王今日销售额12000元
          if (input.includes('销售额')) {
              var daySales = this.parseSalesData(input)
              try{
                const response = await insertDaySale(daySales);
                console.log(response.data);
                this.reply = response.data
              } catch (error) {
                console.log('数据获取失败:', error);
                this.reply = '录入异常'
              }
          }
        },
        askRule(input) {
          //蜘蛛王今日销售额12000元
          if (input.includes('销售额')) {
              var daySales = this.parseSalesData(input)
              if(daySales){
                this.reply = '正在录入'
              }
              insertDaySale(daySales).then(response => {
                 console.log(response.data);
                this.reply = response.data
              }).catch(error => {
                  console.log('数据获取失败:', error);
                  this.reply = '录入异常'
              });
              setTimeout(() => {
                  this.messages.push({
                  text: this.reply,
                  sender: 'bot-message'
                  });
                  this.scrollToBottom();
              }, 500);
          }
        },
        generateUUID() {
          var d = new Date().getTime();
          var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
          });
          return uuid;
        },
        askSpark(input) {
            var httpUrl = new URL(this.url);
            var host = httpUrl.host
            var date = new Date().toGMTString()
            var algorithm = 'hmac-sha256'
            var headers = 'host date request-line'
            var signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${httpUrl.pathname} HTTP/1.1`
            var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, this.apiSecret)
            var signature = CryptoJS.enc.Base64.stringify(signatureSha)
            var authorizationOrigin = `api_key="${this.apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
            var authorization = btoa(authorizationOrigin)
            var authUrl = `${this.url}?authorization=${authorization}&date=${date}&host=${host}`
            var ws = new WebSocket(authUrl)
            ws.onopen=()=> {
                console.log("网络连接成功")
                var chatInfo = {"header":{"app_id":this.appId,"uid":this.generateUUID()},"parameter":{"chat":{"domain":"generalv3.5","temperature":0.5,"max_tokens":1024}},"payload":{"message":{"text":[{"role":"user","content":input}]}}}
                ws.send(JSON.stringify(chatInfo))
            }

            ws.onmessage =  (res) =>{
                let resp = JSON.parse(res.data);
                if(resp.header.code == 0){
                  this.reply += resp.payload.choices.text[0].content
                  if(resp.header.status == 0){
                    this.messages.push({
                      text: this.reply,
                      sender: 'bot-message'
                      });
                    //this.scrollToBottom();
                  }else{
                    this.messages[this.messages.length - 1].text = this.reply
                  }
                }else{
                  console.log('header:' + JSON.stringify(resp.header))
                  this.messages.push({
                    text: this.knowledgeBase['默认'],
                    sender: 'bot-message'
                    });
                  this.scrollToBottom();
                }   
            }
            ws.onclose=(res) =>{
                console.log(`网络关闭成功，代码: ${res.code}, 原因: ${res.reason}`);
            }
            ws.onerror=(res) =>{
                  this.messages.push({
                  text: this.knowledgeBase['默认'],
                  sender: 'bot-message'
                  });
                this.scrollToBottom();
                console.log(`网络连接异常，错误: ${res.message || '未知错误'}`);
            }
        },
        getBotReply(input) {
            this.reply = ''
            input = input.toLowerCase().trim();
            this.askKnownledge(input)
            console.log('knowledge_answer:' + this.reply)
            if(this.reply === ''){
              this.askRule(input)
            }
            console.log('rule_answer:' + this.reply)
            if(this.reply === ''){
              this.askSpark(input)
            }
            
        },
        scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messages;
                container.scrollTop = container.scrollHeight;
            });
        },
        // 开始新对话
        startNewChat() {
            this.messages = [
                { text: '您好！我是小西AI助手，请问有什么可以帮您的吗？', sender: 'bot-message' }
            ];
            this.userInput = '';
            this.$nextTick(() => {
                this.scrollToBottom();
            });
        }
    }
}
</script>

<style lang="less">
.bot-container{
    position: fixed;
}
  /* 机器人图标样式 */
    .chatbot-icon {
      width: 60px;
      height: 60px;
      background-color: #4285f4;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
      z-index: 1000;
      transition: all 0.3s ease;
    }
    
    .chatbot-icon:hover {
      transform: scale(1.1);
      box-shadow: 0 6px 16px rgba(0, 0, 0, 0.25);
    }
    
    .chatbot-icon img {
      width: 70%;
      height: 70%;
    }
    
    /* 聊天窗口样式 */
    .chatbot-window {
      position: fixed;
      right: 30px;
      width: 350px;
      height: 500px;
      background-color: white;
      border-radius: 15px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
      display: flex;
      flex-direction: column;
      overflow: hidden;
      z-index: 999;
      transform: translateY(20px);
      opacity: 0;
      transition: all 0.3s ease;
    }
    
    .chatbot-window.active {
      transform: translateY(0);
      opacity: 1;
    }
    
    .chatbot-header {
      background-color: #4285f4;
      color: white;
      padding: 15px;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chatbot-close {
      cursor: pointer;
      font-size: 20px;
    }
    
    .chatbot-messages {
      flex: 1;
      padding: 15px;
      overflow-y: auto;
      background-color: #f9f9f9;
    }
    
    .message {
      margin-bottom: 15px;
      max-width: 80%;
      padding: 10px 15px;
      border-radius: 18px;
      line-height: 1.4;
      word-wrap: break-word;
    }
    
    .bot-message {
      //background-color: #e9e9e9;
      background-color: #a9a0e2;
      border-top-left-radius: 5px;
      align-self: flex-start;
    }
    
    .user-message {
      background-color: #4285f4;
      color: white;
      border-top-right-radius: 5px;
      margin-left: auto;
    }

    .chatbot-input {
      display: flex;
      padding: 10px;
      border-top: 1px solid #eee;
      background-color: white;
      align-items: center;
    }
    
    .chatbot-input-actions {
      display: flex;
      align-items: center;
    }
    
    .new-chat-btn {
      margin-right: 10px;
      padding: 8px;
      background: none;
      border: none;
      cursor: pointer;
      color: #4285f4;
      font-size: 14px;
      display: flex;
      align-items: center;
    }
    
    .new-chat-btn:hover {
      text-decoration: underline;
    }
    
    .chatbot-input input {
      flex: 1;
      padding: 10px 15px;
      border: 1px solid #ddd;
      border-radius: 25px;
      outline: none;
      font-size: 14px;
    }
    
    .chatbot-input button {
      margin-left: 10px;
      padding: 10px 15px;
      background-color: #4285f4;
      color: white;
      border: none;
      border-radius: 25px;
      cursor: pointer;
      transition: background-color 0.2s;
    }
    
    .chatbot-input button:hover {
      background-color: #3367d6;
    }
    
    /* 动画效果 */
    .fade-enter-active, .fade-leave-active {
      transition: opacity 0.5s;
    }
    
    .fade-enter, .fade-leave-to {
      opacity: 0;
    }
</style>
